package com.smart.web.controller;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.smart.dao.Page;
import com.smart.dao.PageRequest;
import com.smart.model.Notice;
import com.smart.model.NoticeCond;
import com.smart.util.StringUtil;

@Controller
public class NoticeController extends BaseController{
	@RequestMapping(value = "admin/notice/list")
	public String listNotice(PageRequest pageRequest, Model model,HttpServletRequest request){
		String typeStr = request.getParameter("type");
		NoticeCond cond = new NoticeCond();
		int type=0;
		if(StringUtil.isNotEmpty(typeStr)) {
			type=Integer.parseInt(typeStr);
		}
		if(type!=0) {cond.setType(type);}
		Page<Notice> page = noticeService.findAll(pageRequest,cond);
		model.addAttribute("page", page);
		model.addAttribute("type", type);
		
		return "admin/notice/list";
	}
	
	@RequestMapping(value = "admin/notice/edit", method=RequestMethod.GET)
	public String preEditNotice(Long id, Model model) {
		if(id!=null){
			Notice Notice = noticeService.findOne(id);
			model.addAttribute("obj", Notice);
		}
		return "admin/notice/edit";
	}
	
	@RequestMapping(value = "admin/notice/edit", method=RequestMethod.POST)
	public String editNotice(Notice form, Model model, RedirectAttributes ra) {
		try {
			Random rand = new Random();
			if(form.getViewCount()==0) {
				int count = rand.nextInt(51)+150;
				form.setViewCount(count);
			}
			noticeService.save(form);
			model.addAttribute("obj", form);
		} catch (Exception e) {
			e.printStackTrace();
		}
		setSuccessMsg(ra);
		return "redirect:edit?id=" + form.getId();
	}
	
	@RequestMapping(value = "admin/notice/delete", method=RequestMethod.GET)
	public @ResponseBody String deleteNotice(Long id) {
		noticeService.delete(id);
		return "OK";
	}
	public static void main(String[] args) {
		Random rand = new Random();
		int start= rand.nextInt(51)+150;
		System.out.println(start);
	}

}
